package nio.channel.filechannel;


import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author charwayH
 * FileChannel的写操作
 */
public class FileChannelDemo2 {
    public static void main(String[] args) throws IOException {
        // 创建一个FileChannel
        RandomAccessFile aFile = new RandomAccessFile("/Users/charwayh/Desktop/java-myself/hello-nio/src/main/java/channel/01.txt", "rw");
        FileChannel channel = aFile.getChannel();

        // 创建Buffer对象
        ByteBuffer buf = ByteBuffer.allocate(1024);
        String newData = "New String to write to file...";
        buf.clear();

        // 写入内容
        buf.put(newData.getBytes());
        buf.flip();

        // FileChannel完成最终实现
        while (buf.hasRemaining()){
            channel.write(buf);
        }
        //关闭
        channel.close();
        aFile.close();
    }
}
